package com.scs.application.modules.sys.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.scs.application.core.service.BaseServiceImpl;
import com.scs.application.core.utils.UserUtils;
import com.scs.application.modules.sys.entity.Menu;
import com.scs.application.modules.sys.entity.Role;
import com.scs.application.modules.sys.entity.User;
import com.scs.application.modules.sys.mapper.MenuMapper;
import com.scs.application.modules.sys.properties.SystemProperties;
import com.scs.application.modules.sys.service.MenuService;
import com.scs.application.modules.sys.service.RoleService;
import com.scs.application.modules.sys.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@Slf4j
public class MenuServiceImpl extends BaseServiceImpl<MenuMapper, Menu> implements MenuService {

    @Autowired
    private UserService userService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private SystemProperties systemProperties;

    @Override
    public String getDesignMenu() {
        return listToTree(JSONArray.parseArray(JSON.toJSONString(this.list())),"id","parentId","children").toJSONString();
    }

    /**
     * 获取用户菜单
     *
     * @param
     * @return
     */
    @Override
    public List<Menu> getUserMenu() {
        if (UserUtils.isAdmin()) {
            return this.list();
        }
        return baseMapper.getUserMenu(UserUtils.currentUser().getId());
    }

    @Override
    public List<Menu> listByUser(String userId) {
        User user = userService.getById(userId);
        if (user != null && "admin".equalsIgnoreCase(user.getCode())) {
            return this.list();
        }
        return baseMapper.getUserMenu(userId);
    }

    @Override
    public List<Menu> listByRole(String roleId) {
        Role role = roleService.getById(roleId);
        if (role!=null && "admin".equalsIgnoreCase(role.getCode())) {
            return this.list();
        }
        return baseMapper.getRoleMenu(roleId);
    }

    /**

     - listToTree
     - <p>方法说明<p>
     - 将JSONArray数组转为树状结构
     - @param arr 需要转化的数据
     - @param id 数据唯一的标识键值
     - @param pid 父id唯一标识键值
     - @param child 子节点键值
     - @return JSONArray
     */
    public static JSONArray listToTree(JSONArray arr,String id,String pid,String child){
        JSONArray r = new JSONArray();
        JSONObject hash = new JSONObject();
        //将数组转为Object的形式，key为数组中的id
        for(int i=0;i<arr.size();i++){
            JSONObject json = (JSONObject) arr.get(i);
            hash.put(json.getString(id), json);
        }
        //遍历结果集
        for(int j=0;j<arr.size();j++){
            //单条记录
            JSONObject aVal = (JSONObject) arr.get(j);
            //在hash中取出key为单条记录中pid的值
            JSONObject hashVP = (JSONObject) hash.get(aVal.get(pid).toString());
            //如果记录的pid存在，则说明它有父节点，将她添加到孩子节点的集合中
            if(hashVP!=null){
                //检查是否有child属性
                if(hashVP.get(child)!=null){
                    JSONArray ch = (JSONArray) hashVP.get(child);
                    ch.add(aVal);
                    hashVP.put(child, ch);
                }else{
                    JSONArray ch = new JSONArray();
                    ch.add(aVal);
                    hashVP.put(child, ch);
                }
            }else{
                r.add(aVal);
            }
        }
        return r;
    }

    @Override
    public List<Menu> list() {
        QueryWrapper queryWrapper = Wrappers.query();
        queryWrapper.orderByAsc("sort");
        return this.list(queryWrapper);
    }


    @Override
    public boolean saveOrUpdate(Menu entity) {
        return super.saveOrUpdate(entity);
    }
}
